/* 
Copyright (c) 2004,2005, 2006, 2007, 2008 University of Illinois 

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
AccessibilityExtension.ns(function() { with (AccessibilityExtension.LIB) {

	var AE = AccessibilityExtension.ns;  

	function CSSParser(style_str, dom){
		this.fontsize = new Array();
		this.filename = new Array();
		this.fileLineNo = new Array();
		
		if (style_str && typeof style_str == "object"){
			dom = style_str;
			style_str = "all";
		}else if (!dom) dom = dw.getDocumentDOM();
		switch(style_str){
			case "*":
			case "all":
			case "document":
				style_str = this.getEmbeddedCSSStyle(dom);
				style_str += this.getLinkedCSSStyle(dom);
				style_str += this.getImportCSSStyle(dom);
				break;
			case "styles":
				style_str = this.getEmbeddedCSSStyle(dom);
				style_str = this.getImportCSSStyle(dom);
				break;
			case "links":
				style_str = this.getLinkedCSSStyle(dom);
				break;
		}
	}	
	CSSParser.prototype = {
		fontsize : null,
		filename : null,
		fileLineNo: null,
		
		lineNo : function(style_str, pos) {
			var count = 1;
			var posOfNewLine = style_str.lastIndexOf('\n', pos - 1);
			if (posOfNewLine >=0 ) {
				while (posOfNewLine >=0 ) {
					count ++;
					posOfNewLine = style_str.lastIndexOf('\n', posOfNewLine - 1);
				}
			} else {
				posOfNewLine = style_str.lastIndexOf('\r', pos - 1);
				while (posOfNewLine >=0 ) {
					count ++;
					posOfNewLine = style_str.lastIndexOf('\r', posOfNewLine - 1);
				}
			}
			return count;
		},
		lineSeperator : function(style_str, pos) {
			var posOfNewLine = style_str.lastIndexOf('\n', pos - 1);
			if (posOfNewLine >=0 ) { return posOfNewLine; }
			posOfNewLine = style_str.lastIndexOf('\f', pos - 1);
			if (posOfNewLine >=0 ) { return posOfNewLine; }
			posOfNewLine = style_str.lastIndexOf('\r', pos - 1);
			if (posOfNewLine >=0 ) { return posOfNewLine; }
			return 1;
		},
		fileContentsParser : function(style_str, fromFileName) {
			var cssname = '';
			var count = 0;
			var pos = style_str.indexOf('font-size');
			while (pos > 0) {
				this.fileLineNo[count] = this.lineNo(style_str, pos);
				this.fontsize[count] = style_str.charAt(pos + 10);
				for (var i = 1, cssname = ''; i < 6 && style_str.charAt(pos + 10 + i) != ';'; i++) {
					this.fontsize[count] = this.fontsize[count] + style_str.charAt(pos + 10 + i);
				}
	
				var startParen = style_str.lastIndexOf('{', pos);
				//var posOfName = style_str.lastIndexOf('\n', startParen - 1);
				var posOfName = this.lineSeperator(style_str, startParen - 1);
				for (var i = 0; i < 120 && style_str.charAt(posOfName + 1 + i) != '{'; i++) {
					cssname = cssname + style_str.charAt(posOfName + 1 + i);
				}
				this.fontsize[count] = cssname + ' {font-size:' +  this.fontsize[count] + '}';
				this.filename[count] = fromFileName;
				
				count++;
				pos = style_str.indexOf('font-size', pos + 9);
			}	
			pos = style_str.indexOf('width');
			while (pos > 0) {
				if (style_str.charAt(pos - 1) != '-') { //ignore things like border-width
					this.fileLineNo[count] = this.lineNo(style_str, pos);
					this.fontsize[count] = style_str.charAt(pos + 6);
					for (var i = 1; i < 6 && style_str.charAt(pos + 6 + i) != ';'; i++) {
						this.fontsize[count] = this.fontsize[count] + style_str.charAt(pos + 6 + i);
					}
		
					var startParen = style_str.lastIndexOf('{', pos);
					//var posOfName = style_str.lastIndexOf('\n', startParen - 1);
					var posOfName = this.lineSeperator(style_str, startParen - 1);
					for (var i = 0, cssname = ''; i < 120 && style_str.charAt(posOfName + 1 + i) != '{'; i++) {
						cssname = cssname + style_str.charAt(posOfName + 1 + i);
					}
					this.fontsize[count] = cssname + ' {width:' +  this.fontsize[count] + '}';
					this.filename[count] = fromFileName;
					
					count++;
				}
				pos = style_str.indexOf('width', pos + 5);
			}		
		},
		getLinkedCSSStyle : function(dom){
			var links = dom.getElementsByTagName("LINK");
			var style_str = "";
			if (links.length){
				var contents;
				var fromFileName;
				var i, len = links.length;
				for (i=0; i<len; i++){
					if (links[i].rel.toLowerCase() == "stylesheet" && links[i].href){
						
						if (links[i].getAttribute("href").indexOf('http') >= 0 ) { //absolute path
							fromFileName = links[i].getAttribute("href");
						} else {
							 if (links[i].getAttribute("href").substring(0,1) == "/") { // relative to domain
									var pos = dom.URL.indexOf("/", dom.URL.indexOf('http')+ 8);
									if (pos == -1){ pos = dom.URL.length;alert(pos) }
									fromFileName = dom.URL.substr(0, pos) + links[i].getAttribute("href");
							 	
							 } else { //relative path
								fromFileName = dom.URL.substr(0, dom.URL.lastIndexOf("/")+1) + links[i].getAttribute("href");
							 }
						}
						contents = ReturnText(fromFileName);
						if (contents) this.fileContentsParser(contents, fromFileName);	
					}
				}
			}
			return (style_str == "") ? "" : style_str;
		},
		getImportCSSStyle : function(dom){
			try {
				var styles = dom.getElementsByTagName("STYLE");
				var style_str = "";
				if (styles.length){
					var contents;
					var fromFileName;
					var i, len = styles.length;
					for (i=0; i<len; i++){
						var istart = styles[i].innerHTML.toLowerCase().indexOf('@import');
						while (istart >= 0){
							var iend = styles[i].innerHTML.indexOf(';', istart) - istart;
							var tmp = styles[i].innerHTML.substr(istart, iend);
							tmp = tmp.replace('(',' ');
							tmp = tmp.replace(')',' ');
							tmp = tmp.replace(';','');
							tmp = tmp.replace(' url ',' ');
							tmp = cleanSpaces(tmp);
							fromFileName = dom.URL.substr(0, dom.URL.lastIndexOf("/")+1) + tmp.substring(9, tmp.length - 1);
							contents = ReturnText(fromFileName);
							if (contents) this.fileContentsParser(contents, fromFileName);	
							istart = styles[i].innerHTML.toLowerCase().indexOf('@import', iend + istart);
						}
					}
				}
				return (style_str == "") ? "" : style_str;
			} catch (ex) {
				accessext_consoleDump('getImportCSSStyle exception: ' + ex);
			}
		},
		getEmbeddedCSSStyle : function(dom){
			var styles = dom.getElementsByTagName("STYLE");
			var style_str = "";
			if (styles.length){
				var i, len = styles.length;
				for (i=0; i<len; i++) style_str += styles[i].innerHTML;
			}
			return (style_str == "") ? "" : style_str;
		},
		getInlineCSSStyle : function(element){
			return (element.style == undefined) ? "" : element.style;
		}
	}
AccessibilityExtension.LIB.extend(AccessibilityExtension.LIB,
{	
	newCSSParser: function(style_str, dom) {
		var n = new CSSParser(style_str, dom);
		return n; 
	},
	
	ReturnText: function(filename) {
		try {
			var oRequest = new XMLHttpRequest();
			var sURL  = filename; 
			
			oRequest.open("GET",sURL,false);
			oRequest.setRequestHeader("User-Agent",navigator.userAgent);
			oRequest.send(null)
			
			if (oRequest.status==200) {
				return oRequest.responseText;
			}
			else {
				accessext_consoleDump(filename + " Error executing XMLHttpRequest call, does the file exist?");
			}
		} catch (ex) {
			accessext_consoleDump('ParseDocument exception: ' + ex);
		}
	}
});
}});